package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/goinggo/mapstructure"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/config"
		"github.com/dgrijalva/jwt-go"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/service"
	"zimuzu_cvn_web_api/router/api"
)

func TrackLog() gin.HandlerFunc {
	return func(c *gin.Context){
		Log("Info", " [Start Function]: ", c.Request.URL.Path)
		Log("Info", " [params]: ", c.Request.URL.RawQuery)
		c.Next()
	}
}

//验证token中间件
func AuthMiddleware()gin.HandlerFunc {
	return func(c *gin.Context){
		if err := CheckTokenLogin(c);err != nil{
			api.SendResponse(c, err, nil)
			c.Abort()
			return
		}
		c.Next()
	}
}

func parseToken(s string) (*jwt.Token, error) {
	fn := func(token *jwt.Token) (interface{}, error) {
		return []byte(config.C.JwtSecret), nil
	}
	return jwt.Parse(s, fn)
}

func CheckTokenLogin(c *gin.Context)error{
	//从header中获取token
	tokenStr := c.Request.Header.Get("Authorization")
	if len(tokenStr) == 0{
		errno.LoginOut.Info = "token无效"
		return errno.LoginOut
	}
	//获取验证之后的结果
	token, err := parseToken(tokenStr)
	if err != nil {
		Log("Info", "", tokenStr)
		errno.LoginOut.Info = "token格式错误"
		return errno.LoginOut
	}
	//如果验证结果是false直接返回token错误我 如果成功则继续下一个handler
	if token.Valid {
		claim := service.TokenClaims{}
		mapstructure.Decode(token.Claims.(jwt.MapClaims),&claim)
		loginToken , errGetSign := service.GetLoginTokenCache(claim.Uid, service.LoginPlatformPc)
		if errGetSign != nil || tokenStr != loginToken{
			return errno.LoginOut
		}
		c.Set("userId", claim.Uid)
		return nil
	} else {
		errno.LoginOut.Info = "token verify inValid"
		return errno.LoginOut
	}
}